﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace DotNETX.Utility
{
    public static class StructUtils
    {
        public static T BytesToStuct<T>(byte[] bytes, Type type)
            where T : struct
        {
            return BytesToStuct<T>(bytes, 0, type);
        }

        public static T BytesToStuct<T>(byte[] bytes, int index, Type type)
            where T : struct
        {
            object obj = BytesToStuct(bytes, index, type);
            return (T)obj;
        }

        public static object BytesToStuct(byte[] bytes, Type type)
        {
            return BytesToStuct(bytes, 0, type);
        }

        public static object BytesToStuct(byte[] bytes, int index, Type type)
        {
            int size = Marshal.SizeOf(type);
            if (size > bytes.Length)
            {
                return null;
            }
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.Copy(bytes, index, structPtr, size);
            object obj = Marshal.PtrToStructure(structPtr, type);
            Marshal.FreeHGlobal(structPtr);
            return obj;
        }

        public static byte[] StructToBytes(object structObj)
        {
            int size = Marshal.SizeOf(structObj);
            byte[] bytes = new byte[size];
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(structObj, structPtr, false);
            Marshal.Copy(structPtr, bytes, 0, size);
            Marshal.FreeHGlobal(structPtr);
            return bytes;
        }
    }
}
